/**
 * WebSocket 工具类
 * 用于管理客服端的 WebSocket 连接
 */

export class ServiceWebSocket {
  constructor(serviceId = '1001') {
    this.serviceId = serviceId
    this.ws = null
    this.userConnections = new Map() // 存储用户连接
    this.onUserConnected = null
    this.onMessage = null
    this.onError = null
    this.onClose = null
    this.reconnectTimer = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.isManualClose = false // 标记是否为手动关闭
  }

  /**
   * 连接到 WebSocket 服务器
   */
  connect() {
    // 如果已经存在连接，先关闭它
    if (this.ws) {
      // 如果连接正在打开或已打开，先关闭
      if (this.ws.readyState === WebSocket.CONNECTING || this.ws.readyState === WebSocket.OPEN) {
        console.log('检测到已存在的连接，先关闭旧连接')
        this.isManualClose = true // 标记为手动关闭
        this.ws.close()
      }
      this.ws = null
    }
    
    // 清除重连定时器
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
    
    // 重置手动关闭标志
    this.isManualClose = false
    
    const wsUrl = `ws://127.0.0.1:8000/ws/service${this.serviceId}`
    
    try {
      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        console.log('客服 WebSocket 连接成功')
        this.reconnectAttempts = 0
        if (this.reconnectTimer) {
          clearTimeout(this.reconnectTimer)
          this.reconnectTimer = null
        }
      }

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          
          // 如果是用户连接通知
          if (data.userid && data.name) {
            this.userConnections.set(data.userid, {
              userId: data.userid,
              name: data.name,
              connectedAt: new Date()
            })
            if (this.onUserConnected) {
              this.onUserConnected(data)
            }
          } 
          // 如果是消息
          else if (this.onMessage) {
            this.onMessage(data)
          }
        } catch (error) {
          console.error('解析 WebSocket 消息失败:', error)
        }
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误:', error)
        if (this.onError) {
          this.onError(error)
        }
      }

      this.ws.onclose = () => {
        console.log('WebSocket 连接已关闭')
        if (this.onClose) {
          this.onClose()
        }
        // 只有非手动关闭时才自动重连
        if (!this.isManualClose) {
          this.reconnect()
        } else {
          console.log('手动关闭连接，不进行重连')
          this.isManualClose = false // 重置标志
        }
      }
    } catch (error) {
      console.error('创建 WebSocket 连接失败:', error)
      if (this.onError) {
        this.onError(error)
      }
    }
  }

  /**
   * 自动重连
   */
  reconnect() {
    // 如果已经连接，不需要重连
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      console.log('WebSocket 已连接，取消重连')
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer)
        this.reconnectTimer = null
      }
      return
    }
    
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('达到最大重连次数，停止重连')
      return
    }

    this.reconnectAttempts++
    const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000) // 指数退避，最大30秒
    
    console.log(`${delay}ms 后尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
    
    this.reconnectTimer = setTimeout(() => {
      // 重连前再次检查是否已连接
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        this.connect()
      }
    }, delay)
  }

  /**
   * 发送消息给指定用户
   */
  sendMessage(toUserId, message, extraData = {}) {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      console.error('WebSocket 未连接')
      return false
    }

    const messageData = {
      from: `service${this.serviceId}`,
      to: toUserId,
      message: message,
      timestamp: new Date().toISOString(),
      ...extraData
    }

    try {
      this.ws.send(JSON.stringify(messageData))
      return true
    } catch (error) {
      console.error('发送消息失败:', error)
      return false
    }
  }

  /**
   * 获取所有连接的用户列表
   */
  getConnectedUsers() {
    return Array.from(this.userConnections.values())
  }

  /**
   * 断开连接
   */
  disconnect() {
    // 标记为手动关闭
    this.isManualClose = true
    
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
    
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    
    this.userConnections.clear()
  }

  /**
   * 检查连接状态
   */
  isConnected() {
    return this.ws && this.ws.readyState === WebSocket.OPEN
  }
}

